﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

public partial class QQOnline : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext.Current.Session["LastUrl"] = "./QQOnline.aspx";
        if (!this.IsPostBack)
        {
            this.Button4.Enabled = false;
        }
        else
        {
            this.Button4.Enabled = true;
        }
        if (User.Identity.IsAuthenticated)
        {
            global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
            {
                if(user.IsValidate)
                {
                    this.QQListView.Visible = true;
                    return;
                }
            }
        }
        this.QQListView.Visible = false;
        
    }

    const string ViewStateConst = "QQService";


    protected void qqListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        foreach (ListViewDataItem item in this.QQListView.Items)
        {
            this.QQListView.UpdateItem(item.DataItemIndex, false);
        }
    }

    protected void qqListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        // These could also be defined in the aspx and just referenced here with like e.NewValues["ListIndex"]..  but if
        //  we have to do them manually for the Delete anyway, might as well do them all manually and keep them together 
        //   in the code-behind.
        this.objQQService.UpdateParameters.Clear();
        objQQService.UpdateParameters.Add(new Parameter("ListIndex", TypeCode.Int16, e.ItemIndex.ToString()));
        objQQService.UpdateParameters.Add(new Parameter("Number", TypeCode.String, ((TextBox)this.QQListView.Items[e.ItemIndex].FindControl("NumberTextBox")).Text.Trim()));
        objQQService.UpdateParameters.Add(new Parameter("NickName", TypeCode.String, ((TextBox)this.QQListView.Items[e.ItemIndex].FindControl("NickNameTextBox")).Text.Trim()));
    }

    protected void qqListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        // The ListIndex parameter could have been defined in the aspx - DeleteParameters collection of the ObjectDataSource,
        //  but then we'd have to reference it here by objOfficer.DeleteParameters["ListIndex"].DefaultValue - and unfortunately
        //   DefaultValue only accepts strings (regardless of Parameter type)
        objQQService.DeleteParameters.Clear();
        objQQService.DeleteParameters.Add(new Parameter("ListIndex", TypeCode.Int16, e.ItemIndex.ToString()));
    }

    protected void objQQService_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        // pass in ViewState for accessing from the class
        if (ViewState[ViewStateConst] != null)
        {
            e.ObjectInstance = ViewState[ViewStateConst] as QQService;
        }
        else
        {
            global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
            ServiceManager serviceManager = ServiceManager.LoadFromFile(user.ServiceFileName);
            if (serviceManager != null && serviceManager.QQService != null)
            {
                e.ObjectInstance = serviceManager.QQService;
            }
            else
            {
                e.ObjectInstance = new QQService();
            }
            ViewState[ViewStateConst] = e.ObjectInstance;
        }
    }

    private string baseAddress = @"http://wpa.qq.com/pa?p=1:{0}:5";

    private bool IsQQOnline(string number)
    {
        string url = string.Format(baseAddress, number);
        int len = HtmlUtility.GetResponseLength(url);
        if (len < 1248)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private delegate void DoStuff(string s1, string s2);

    private void SendOut(string s1, string s2)
    {
        SendMail.Send(MailAccounts.GetInstance().QQ, "Update:" + s1,
           s2, false, ConstStrings.RootMail);
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        Utility.CheckLoginAndRedirect();
        global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
        ServiceManager serviceManager = ServiceManager.LoadFromFile(user.ServiceFileName);
        this.qqListView1_ItemCommand(null, null);

        int original = 0;
        if (serviceManager.QQService != null)
        {
            original = serviceManager.QQService.Entities.Count * QQService.ItemPrice;
        }
        serviceManager.QQService = ViewState[ViewStateConst] as QQService;
        user.ConsumedMoneyEveryMonth = user.ConsumedMoneyEveryMonth - original +
                                            serviceManager.QQService.Entities.Count * QQService.ItemPrice;

        DataManager dataMan = new DataManager(user.ServiceFileName, typeof(ServiceManager));
        dataMan.SaveData(serviceManager);

        this.Button4.Enabled = false;
        DoStuff action = new DoStuff(SendOut);
        action.BeginInvoke(user.PhoneNumber, serviceManager.QQService.SerializeToString(), null, null);
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        Utility.CheckLoginAndRedirect();

        global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
        if (user.Money - user.ConsumedMoneyEveryMonth < QQService.ItemPrice)
        {
            this.Label2.ForeColor = Color.Red;
            this.Label2.Text = ConstStrings.NotEnoughMoney;
        }

        string qq = this.TextBox2.Text.Trim();
        string nickName = this.TextBox3.Text.Trim();
        this.TextBox2.Text = "";
        this.TextBox3.Text = "";

        if (!Master.IsNumber(qq))
        {
            this.Label2.ForeColor = System.Drawing.Color.Red;
            this.Label2.Text = ConstStrings.InputCorrentNumber;
            return;
        }

        QQService service = ViewState[ViewStateConst] as QQService;
        if (service == null)
        {
            service = new QQService();
            ViewState[ViewStateConst] = service;
        }

        service.Entities.Add(new QQServiceEntity() { Number = qq, NickName = nickName });
        this.QQListView.DataBind();
        foreach(ListViewDataItem item in this.QQListView.Items)
        {
            this.QQListView.UpdateItem(item.DataItemIndex, false);
        }
        //number = number + "@139.com";
        //// TODO: more input validation.
        //this.RegisterUserInput(qq, number);
        //label.ForeColor = Color.Blue;
        //label.Text = string.Format(NotificationMessageFormat, "侦听QQ" + qq + "的上线情况");
    }
}